package com.tamakloe.guestbook;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MessageDownloadForm extends Form {
	private static final String FIELD_RESULT = "result";

	public MessageDownloadForm(){
		
	}

	// Form actions -------------------------------------------------------------------------------
	
	public String processGreeting(Greeting g){
		return  g.getDataInCSV();
	}
//http://www.roseindia.net/jsp/downloadcsv.shtml
	
	@SuppressWarnings("unchecked")
	public void downloadMessages(HttpServletRequest req, HttpServletResponse resp) {
		int messageCount = 0;
		String filename = DateUtils.nowFilename() + ".csv";
		String csvContents ="ID,Date,Name,Email,Message" + "\n";
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + Greeting.class.getName()
				+ " order by date desc ";
		List<Greeting> greetings = (List<Greeting>) pm.newQuery(query).execute();
		try{
			for (Greeting g : greetings){
				csvContents += processGreeting(g);
			}
			
		}catch(Exception e){
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));	
			setError(FIELD_RESULT, sw.toString());
		}finally{
			byte requestBytes[] = csvContents.getBytes();
			ByteArrayInputStream bis = new ByteArrayInputStream(requestBytes);
			resp.reset();
			resp.setContentType("application/text");
			resp.setHeader("Content-disposition","attachment; filename=" +filename);
			byte[] buf = new byte[1024];
			int len;
			try {
				while ((len = bis.read(buf)) > 0){
					resp.getOutputStream().write(buf, 0, len);
				}

			} catch (IOException e) {
				StringWriter sw = new StringWriter();
				e.printStackTrace(new PrintWriter(sw));	
				setError(FIELD_RESULT, sw.toString());
			}finally{
				try{
					bis.close();
					resp.getOutputStream().flush(); 
				}catch(IOException e){
					StringWriter sw = new StringWriter();
					e.printStackTrace(new PrintWriter(sw));	
					setError(FIELD_RESULT, sw.toString());
				}finally{
					setMessage(FIELD_RESULT, "Successfully downloaded " + messageCount +  " messages");
				}
				
			}
			
		}
		
	}


}
